<?php

namespace app\api\controller;

use app\admin\model\information\Warehouse;
use app\common\controller\Api;
use think\Log;
use app\common\model\Material;
use app\admin\model\inventory\MaterialList;

use app\admin\model\inventory\Procure;
use app\common\model\Inventory;

use app\admin\model\Mcode;
use think\Db;
use think\Exception;
use app\admin\model\inventory\Wmskc;
/**
 * mes接口
 */
class Mesapi extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    protected $mesInFactoryCodes = [10395,14728];//mes 外包、综合外包车间id
    protected $mesInFactoryNames = [
        10395 => "外包车间",
        14728 => "综合外包车间"
    ];

    public function _initialize()
    {
        $this->request->filter('trim,strip_tags,htmlspecialchars');
        parent::_initialize();
    }
    
    public function test(){
        echo 'ok';
    }
    /* 
     * 参数名 bill_str
     * [
     *  billno:'单号',
     *  bdate:2023-12-08,
     *  explanation:'摘要'
     *  detail:[
     *      [
     *          fitemid:123,
     *          fqty:12.5,
     *          note:'备注'
     *      ],
     *      [
     *          fitemid:123,
     *          fqty:12.5,
     *          note:'备注'
     *      ],
     *  ]
     * ]
     * MES领料出库 - 拣货任务
     * */
    public function addOut(){
        $post_str = $this->request->post('bill_str','');
        if(!$post_str){
            $this->error('bill_str参数不能为空');
        }
        
        $post_arr = json_decode(htmlspecialchars_decode($post_str),true);
        Log::record('MES领料出库,提交参数',$post_arr);
        
        if(!isset($post_arr['billno'])||!$post_arr['billno']){
            $this->error('billno参数不能为空');
        }
        
        if(!isset($post_arr['bdate'])||!$post_arr['bdate']){
            $this->error('bdate参数不能为空');
        }
        
        if(!isset($post_arr['detail'])||!count($post_arr['detail'])){
            $this->error('detail参数不能为空');
        }
        
        $check = Material::where('source_code',$post_arr['billno'])->value('id');
        if($check){
            $this->error('已存在单号：'.$post_arr['billno']);
        }
        
        Db::startTrans();
        try {
            $material = Material::create([
                'material_code' => Mcode::getCode(2),
                'source_code' => $post_arr['billno'],
                'order_date' => $post_arr['bdate'],
                'remark' => $post_arr['explanation']
            ]);
            
            if($post_arr['detail']){
                foreach ($post_arr['detail'] as $detail){
                    MaterialList::create([
                        //'warehouse_id':0,//外包车间仓
                    ]);
                }
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        
        
    }
    
    /*
     * 删除出库 - 
     *   */
    public function delOut(){
        $billno = $this->request->post('billno','');
        if(!$billno){
            $this->error('单号不能为空');
        }
        
        
    }
    
    /*
     * 产品入库  - 入库任务 
     {
        "billno":"123",
        "bdate":"202333-12-09",
        "work_fInterID":123,
        "work_order_code":work00001,
        "explanation":"摘要",
        "detail":[
            {
                "fitemid":1234,
                "fqty":12.5,
                "note":"备注"
            },
            {
                "fitemid":123,
                "fqty":12.5,
                "note":"备注"
            }
        ]
    }
    //失败
    {
    	"code": 0,
    	"msg": "不存在物料内码123",
    	"time": "1702017611",
    	"data": null
    }
    //成功
    {
    	"code": 1,
    	"msg": "",
    	"time": "1702018115",
    	"data": "MIN202312080011"
    }
     *   */
    public function addIn(){
        $post_arr = $this->request->param();
        if(!$post_arr){
            $this->error('参数不能为空');
        }
        Log::error('MES产品入库,提交参数');
        Log::error($post_arr);
        
        if(!isset($post_arr['billno'])||!$post_arr['billno']){
            $this->error('billno参数不能为空');
        }
        
        if(!isset($post_arr['bdate'])||!$post_arr['bdate']){
            $this->error('bdate参数不能为空');
        }
        
        if(!isset($post_arr['work_fInterID'])||!$post_arr['work_fInterID']){
            $this->error('work_fInterID参数不能为空');
        }

        if(!isset($post_arr['work_order_code'])||!$post_arr['work_order_code']){
            $this->error('work_order_code参数不能为空');
        }
        
        if(!isset($post_arr['detail'])||!count($post_arr['detail'])){
            $this->error('detail参数不能为空');
        }
        
        // if(!isset($post_arr['department_id'])||!$post_arr['department_id']){
        //     $this->error('department_id参数不能为空');
        // }
        $factory_code = isset($post_arr['factory_code'])?$post_arr['factory_code']:10395;
        if(!$factory_code){
            $factory_code = 10395;
        }
        if(!in_array($factory_code,$this->mesInFactoryCodes)){
            $this->error('车间ID非指定车间');
        }
        
        $check = Procure::where([
            'warehousing_code' => $post_arr['billno'],
            'type' => 1
        ])
        ->value('id');
        if($check){
            $this->error('已存在单号：'.$post_arr['billno']);
        }
        
        //$order_code = Mcode::getCode(3);//自动生成入库单号
        Db::startTrans();
        try {
            if($post_arr['detail']){
                foreach ($post_arr['detail'] as $i=>$detail){
                    $inventory = Inventory::get($detail['fitemid']);
                    if(!$inventory){
                        exception('不存在物料内码'.$detail['fitemid']);
                    }
                    if(!$inventory->fCoefficient){
                        exception("物料".$inventory->name."未设置计量单位、换算率,请核实");
                    }
                    
                    $fqty = floatval($detail['fqty']);
                    if($fqty<=0){
                        exception('物料'.$inventory->name.'数量异常');
                    }
                    
                    //入库任务用于质检通过
                    $procure = Procure::create([
                        'source_code' => $post_arr['work_order_code'],//生产任务单
                        'FInterID' => $post_arr['work_fInterID'],//生产任务单内码
                        'auto_id' => $post_arr['work_fInterID'],//生产任务单内码
                        'warehousing_code' => $post_arr['billno'],
                        'order_date' => substr($post_arr['bdate'],0,10),
                        'warehousing_date' => substr($post_arr['bdate'],0,10),
                        'factory_code' => $factory_code,//10395,
                        'factory_name' => $this->mesInFactoryNames[$factory_code],
                        'row_id' => $i+1,
                        'fItemId' => $detail['fitemid'],
                        'inventory_number' => $inventory->number,
                        'store_quantity' => $detail['fqty'],//常用数量
                        'quantity' => $detail['fqty']*$inventory->fCoefficient,//基本数量
                        'warehousing_quantity' => 0,//已入库数0
                        'no_quantity' => $detail['fqty']*$inventory->fCoefficient,
                        'sh_time'=> substr($post_arr['bdate'],0,10),
                        'remark' => $post_arr['explanation'],
                        'b_remark' => $detail['note'],
                        'cBatch' => $detail['batch'],
                        'unit_price' => 0,
                        'total_price' => 0,
                        'warehouse_id' => 7676,//成品仓
                        'shelves_id' => 1,//待检区
                        'status' => 2,//待质检
                        'type' => 1 //mes
                    ]);
                    $procure->auto_id = $procure->id;
                    $procure->save();
                    
                    $kcData = [
                        'code'=>$post_arr['billno'],
                        'code_date'=>substr($post_arr['bdate'],0,10),
                        'inv_number'=>$inventory->number,
                        'cBatch' => $detail['batch'],
                        'quantity'=> $detail['fqty']*$inventory->fCoefficient,
                        'warehouse_id'=>7676,
                        'shelves_id'=>1
                    ];
                    //更新本地库存
                    Wmskc::OperateWmsKc($kcData, 'inc', 14,'MES产品入库增库存');

                    Log::info($post_arr['billno'],'MES产品入库,成功');
                }
            }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            Log::error('MES产品入库,失败原因:'.$e->getMessage());
            $this->error($e->getMessage());
        }
        $this->success('',['order_code'=>$post_arr['billno']]);
    }
    
    /*
     * 删除入库
                提交参数
     {"billno":"po2023090217"}
             成功
     {
    	"code": 1,
    	"msg": "",
    	"time": "1702020578",
    	"data": null
     }
             失败
     {
    	"code": 0,
    	"msg": "不存在该单号",
    	"time": "1702020475",
    	"data": null
     }
     *   */
    public function delIn(){
        $billno = $this->request->post('billno','');
        if(!$billno){
            $this->error('单号不能为空');
        }
        
        Log::error('MES删除成品入库任务,提交参数:'.$billno);
        $procure = Procure::where([
            'warehousing_code' => $billno,
            'type' => 1
        ])
        ->find();
        if(!$procure){
            $this->error('不存在该单号');
        }

        if($procure->status!=2){
            $this->error('该单号已被下游单据引用');
        }
        
        //关闭状态，就是单被做过
        // if(db('temporary')->where([
        //     'source_code' => $billno,
        //     'status' => ['IN',[0,1]]
        // ])->value('id')){
        //     $this->error('该单号已被下游单据引用');
        // }
        Db::startTrans();
        try{
            $kcData = [
                'code'=>$procure->warehousing_code,
                'code_date'=>$procure->order_date,
                'inv_number'=>$procure->inventory_number,
                'cBatch' => $procure->cBatch,
                'quantity'=> $procure->quantity,
                'warehouse_id'=>7676,
                'shelves_id'=>1
            ];
            //更新本地库存
            Wmskc::OperateWmsKc($kcData, 'dec', 14,'MES产品入库反审删库存');

            //删除
            Procure::where([
                'warehousing_code' => $billno,
                'type' => 1
            ])
            ->delete();

            Db::commit();
            Log::info($billno,'MES删除成品入库任务,成功');
        }catch(Exception $e){
            Db::rollback();
            Log::error('MES产品入库,失败原因'.$e->getMessage());
            $this->error($e->getMessage());
        }
        $this->success();
    }

    //查询
    public function searchIn(){
        $billno = $this->request->post('billno','');
        if(!$billno){
            $this->error('单号不能为空');
        }
        
        Log::info($billno,'MES查询成品入库任务,提交参数');
        $procure = Procure::where([
            'warehousing_code' => $billno,
            'type' => 1
        ])
        ->field('warehousing_code')
        ->find();

        if(!$procure){
            $this->error('不存在该单号');
        }

        // $status = db('temporary')->where([
        //     'source_code' => $billno,
        //     'status' => ['IN',[0,1]]
        // ])->value('status');
        
        $this->success();
    }
}
